var classify_p = 0; // 当前分类
var page_p = 1; // 当前页数
var pages_p = 1; //总页数
var allow = true;  //是否后台获取中
$(function () {
    // 初始化列表
    update_article();
    // 首页分类切换
    $('.classify ul li a').click(function () {
        var click_classify = $(this).attr('value');
        $('.classify ul li').each(function () {
            $(this).removeClass('choose');
        });
        $(this).parent().addClass('choose');
        if (classify_p != click_classify) {
            classify_p = click_classify;
            page_p = 1;
            pages_p = 1;
            allow = false;
            update_article()
        }
    });
    $(window).scroll(function () {
        // 浏览器窗口高度
        var showHeight = $(window).height();
        // 整个网页的高度
        var pageHeight = $(document).height();
        // 页面可以滚动的距离
        var canScrollHeight = pageHeight - showHeight;
        // 页面滚动了多少,这个是随着页面滚动实时变化的
        var nowScroll = $(document).scrollTop();
        if ((canScrollHeight - nowScroll) < 100) {
            if (!allow) {
                allow = true;
                // 如果当前页面数还没到达总页数
                if (page_p <= pages_p) {
                    // 向后端发送请求，查询下一页新闻数据
                    update_article()
                }
            }
        }
    })
});

function update_article() {
    var params = {
        "classify": classify_p,
        "page": page_p
    };
    $.get("/article_list", params, function (resp) {
        allow = false;
        if (resp) {
            pages_p = resp.pagess;
            if (page_p == 1) {
                $(".blog_list").html("");
            }
            page_p += 1;
            for (var i = 0; i < resp.article_list.length; i++) {
                var art = resp.article_list[i];
                var content = "<li class=\"blog\">" +
                    // 标题
                    "<a href='/to_detail/" + art.id + "'><h3>" + art.title + "</h3></a>\n" +
                    // 内容
                    mdSwitch_(art.content).substring(0, 50) + "......<br><br>" +
                    "<a href='/to_writer/" + art.user_id + "' class=\"left\">" + "<img src=\"" + art.user_ava + "\">" + art.user_name + "</a>" +
                    "<ul href=\"#\" class=\"right\" value = " + art.id + ">\n" +
                    "<li><img src=\"../../static/img/coll.png\">" + art.collector + "</li>" +
                    "<li  class='like_article'><img src=\"../../static/img/like.png\">" + art.praise + "</li>\n" +
                    "<li><img src=\"../../static/img/clicks.png\">" + art.clicks + "<li></ul></li>\n";
                $(".blog_list").append(content);
            }
        }
    })
}

function mdSwitch_(art_content) {
    var converter = new showdown.Converter();
    var html = converter.makeHtml(art_content).replace(/<.*?>/ig, "");
    return html
}